<template>
  <div class="app-container">
    <!-- 输入表单 -->
    <el-form label-width="500px">
      <el-form-item label="疫苗名称">
        <el-input v-model="vaccine.vaccineName" style="width: 250px" />
      </el-form-item>
      <el-form-item label="疫苗生产厂商">
        <el-input v-model="vaccine.vaccineManufacturer" style="width: 250px" />
      </el-form-item>
      <el-form-item label="疫苗分类">
        <el-input v-model="vaccine.vaccineClassification" style="width: 250px" />
      </el-form-item>
      <el-form-item>
        <el-button :disabled="saveBtnDisabled" type="primary" @click="saveOrUpdate()">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import vaccineApi from '@/api/vaccine'
export default {
  data() {
    return {
      vaccine: {
        vaccineName: '',
        vaccineManufacturer: '',
        vaccineClassification: ''
      },
      BASE_API: process.env.BASE_API,
      // 初始化作者默认数据
      saveBtnDisabled: false // 保存按钮是否禁用，防止表单重复提交
    }
  },
  // 页面渲染成功
  created() {
    if (this.$route.params.id) {
      this.fetchDataById(this.$route.params.id)
    }
  },
  methods: {
    saveOrUpdate() {
      // 禁用保存按钮
      this.saveBtnDisabled = true
      if (!this.vaccine.id) {
        this.saveData()
      } else {
        this.updateData()
      }
    },
    saveData() {
      console.log(this.vaccine.vaccineName)
      if (this.vaccine.vaccineName === '' ||
         this.vaccine.vaccineManufacturer === '' ||
         this.vaccine.vaccineClassification === '') {
        this.saveBtnDisabled = false
        this.$notify({
          title: '警告',
          dangerouslyUseHTMLString: true,
          type: 'warning',
          duration: 3000,
          message: '含有空项目禁止提交'
        })
      } else {
        // debugger
        vaccineApi.save(this.vaccine).then(response => {
          this.$message({
            type: 'success',
            message: response.message
          })
          this.$router.push({ path: '/vaccine' })
        })
      }
    },
    // 根据id查询记录
    fetchDataById(id) {
      vaccineApi.getById(id).then(response => {
        this.vaccine = response.data.item
      })
    },
    // 根据id更新记录
    updateData() {
      // vaccine数据的获取
      vaccineApi.updateById(this.vaccine).then(response => {
        this.$message({
          type: 'success',
          message: response.message
        })
        this.$router.push({ path: '/vaccine' })
      })
    }
  }
}
</script>
<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
